package br.heusser.productfx.src.dao;

import br.heusser.productfx.src.model.Product;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * @author Diego
 */
public class ProductDAO extends DAO {

    public void insert(Product product) throws Exception {
        EntityManager em = this.getEM();
        try {
            em.getTransaction().begin();
            em.persist(product);
            em.getTransaction().commit();
        } catch (Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }

    public void update(Product product) throws Exception {
        EntityManager em = this.getEM();
        try {
            em.getTransaction().begin();
            em.merge(product);
            em.getTransaction().commit();
        } catch (Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public void delete(Product product) throws Exception {
        EntityManager em = this.getEM();
        try {
            em .getTransaction().begin();
            em.remove(product);
            em.getTransaction().commit();
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public List<Product> list() throws Exception {
        EntityManager em = this.getEM();
        try {
            Query query = em.createQuery("SELECT p FROM Product p");
            List<Product> list = query.getResultList();
            return list;
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
    
    public List<Product> find(String name) throws Exception {
        EntityManager em = this.getEM();
        try {
            Query query = em.createQuery("SELECT p FROM Product p WHERE p.name LIKE :name");
            query.setParameter("name", name+"%");
            List<Product> list = query.getResultList();
            return list;
        } catch(Exception ex) {
            throw ex;
        } finally {
            em.close();
        }
    }
}
